# midserver.py

'''usage: PROGRAM <local_port:remote_url:remote_port>

This program serves as a listener between the DZH client and official
server.

contact me: wanyancan a t gMAiL DTO MOC
'''

import wx, os, sys, logging, getopt, time, threading
##import hexdump
import  wx.lib.mixins.listctrl  as  listmix

class TestListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
    def __init__(self, parent, ID, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0):
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        listmix.ListCtrlAutoWidthMixin.__init__(self)

class clientPanel(wx.Panel):
    def __init__(self, *karg, **kargs):
        wx.Panel.__init__(self, *karg, **kargs)
        vsizer = wx.BoxSizer(wx.VERTICAL)    # 5:1
        self.pklist = TestListCtrl(self, wx.NewId(),
                                 style=wx.LC_REPORT 
                                 #| wx.BORDER_SUNKEN
                                 | wx.BORDER_NONE
                                 | wx.LC_EDIT_LABELS
                                 | wx.LC_SORT_ASCENDING
                                 #| wx.LC_NO_HEADER
                                 #| wx.LC_VRULES
                                 #| wx.LC_HRULES
                                 #| wx.LC_SINGLE_SEL
                                 )
        vsizer.Add(self.pklist, 1, wx.EXPAND, 0)
##        leftsizer.Add(self.drawCav, 5, wx.EXPAND|wx.ALL, 5)
##
##        outsizer.Add(leftsizer, 1, wx.EXPAND)  # left weight : 1
##        # left , separator, right , 
##        outsizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND)  
##
##        rightsizer = wx.BoxSizer(wx.VERTICAL)
##        # upper listbox
##        self.pjlbl = wx.ListBox(self, -1, style=wx.LB_SINGLE)
##        self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnpjDClick, self.pjlbl)
##        rightsizer.Add(self.pjlbl, 1, wx.EXPAND|wx.ALL,5) # '1':1:0
##        # lower listbox
##        self.cjlbl = wx.ListBox(self, -1, style=wx.LB_SINGLE)
##        self.Bind(wx.EVT_LISTBOX_DCLICK, self.OncjDClick, self.cjlbl)        
##        rightsizer.Add(self.cjlbl, 1, wx.EXPAND|wx.ALL,5) # 1:'1':0
##        # Load 'txt' button        
        btRefresh = wx.Button(self, -1, "Load txt data")
##        btRefresh.Bind(wx.EVT_BUTTON, self.loadtxtdata)
        vsizer.Add(btRefresh, 1, wx.EXPAND|wx.ALL,5)    # 1:1:'0'
##        # Show selected datum
##        btShow = wx.Button(self, -1, "Show")
##        btShow.Bind(wx.EVT_BUTTON, self.OnShowBt)
##        rightsizer.Add(btShow, 0, wx.EXPAND|wx.ALL,5) 
##        
##        outsizer.Add(rightsizer, 1, wx.EXPAND)      # right weight :1
        self.SetSizer(vsizer)
        self.SetAutoLayout(True)
                

class MainWindow(wx.Window):
    def __init__(self, parent):
        super(MainWindow, self).__init__(parent,
            style=wx.NO_FULL_REPAINT_ON_RESIZE)
        self.initDrawing()
        self.makeMenu()
        self.bindEvents()

    def initDrawing(self):
        topwin = wx.SashLayoutWindow(
            self, -1, wx.DefaultPosition, (200, 30), 
            wx.NO_BORDER|wx.SW_3D
            )
        topwin.SetDefaultSize((1000, 30))
        topwin.SetOrientation(wx.LAYOUT_HORIZONTAL)
        topwin.SetAlignment(wx.LAYOUT_BOTTOM)
        topwin.SetSashVisible(wx.SASH_TOP, True)
        self.topWindow = topwin

        self.remainingSpace = clientPanel(self, style=wx.SUNKEN_BORDER)

        # set log system
        self.tc = wx.TextCtrl(topwin, -1,
                              style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
        self.log = MyLog(self.tc)
        wx.Log_SetActiveTarget(self.log)

    def bindEvents(self):
        for event, handler in [ \
##                (wx.EVT_LEFT_DOWN, self.onLeftDown), # Start drawing
##                (wx.EVT_LEFT_UP, self.onLeftUp),     # Stop drawing 
##                (wx.EVT_MOTION, self.onMotion),      # Draw
##                (wx.EVT_RIGHT_UP, self.onRightUp),   # Popup menu
                (wx.EVT_SIZE, self.OnSize),          # Prepare for redraw
##                (wx.EVT_IDLE, self.onIdle),          # Redraw
##                (wx.EVT_PAINT, self.onPaint),        # Refresh
                (wx.EVT_SASH_DRAGGED, self.OnSashDrag),
                (wx.EVT_WINDOW_DESTROY, self.OnClose),
                (wx.EVT_CLOSE, self.OnClose)]:
            self.Bind(event, handler)

    def makeMenu(self):
        ''' Make a menu that can be popped up later. '''

    def OnSashDrag(self, event):
        if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
            wx.LogMessage('drag is out of range')
            return
        dgRt = event.GetDragRect()
        wx.LogDebug(str(dgRt))
        self.topWindow.SetDefaultSize((1000, dgRt.height))
        wx.LayoutAlgorithm().LayoutWindow(self, self.remainingSpace)
        self.remainingSpace.Refresh()

    def OnSize(self, evt):
        wx.LayoutAlgorithm().LayoutWindow(self, self.remainingSpace)

    def OnClose(self, evt):
        self.Show(False)
        self.Destroy()
        sys.exit(0)
      

class MainFrame(wx.Frame):
    def __init__(self, parent=None):
        super(MainFrame, self).__init__(parent, title="title not given yet",
            size=(800,600),
            style=wx.DEFAULT_FRAME_STYLE)
        mainwindow = MainWindow(self)

class MyLog(wx.PyLog):
    def __init__(self, textCtrl, logTime=False):
        wx.PyLog.__init__(self)
        self.tc = textCtrl
        self.logTime = logTime

    def DoLogString(self, message, timeStamp):
        if self.logTime:
            message = time.strftime("%X", time.localtime(timeStamp)) + \
                      ": " + message
        if self.tc:
            self.tc.AppendText(message + '\n')
        logger.debug(message)            # log to logger as well

class reactorThread(threading.Thread):
    """subthread used for communication with server
"""
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        try:
            pass
        except:
            pass

def window_main():
    app = wx.App()
    frame = MainFrame()
    frame.Show()
    app.MainLoop()

def commandline_check():
    __usage__ = __doc__.replace("PROGRAM", os.path.basename(sys.argv[0]))
    def die_usage(msg=""):
        sys.stderr.write("%s%s\n" % (__usage__, msg))
        sys.exit(1)
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hl:v", ["help", "log=", "verbose"])
    except getopt.GetoptError, e:
        die_usage(str(e))

    logname=None
    logger.setLevel(logging.INFO)
    wx.Log_SetLogLevel(wx.LOG_Info)    
    for o, a in opts:
        if o in ("-h", "--help"): die_usage()
        if o in ("-v", "--verbose"): logger.setLevel(logging.DEBUG); wx.Log_SetLogLevel(wx.LOG_Debug)
        if o in ("-l", "--log"): logname=a; print "log: [%s]" % logname

    if logname: handler=logging.FileHandler(logname)
    else: handler = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

if __name__ == '__main__':
    try:
        logger = logging.getLogger()
        commandline_check()
        window_main()
    except Exception, err:
        print str(err)
        raw_input()
